package org.yannis.app.app1.client;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The util which interaction with cookie
 *
 * @author Yannis Zhao, zhaoyjun0222@gmail.com Date: 2017-01-25
 */
public final class CookieUtils {

    public static final String ROOT_PATH = "/";

    public static void addCookie(HttpServletResponse response, String name,
        String value) {
        Cookie cookie = new Cookie(name, value);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String name,
        String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String path,
        String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String path,
        String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String domain,
        String path, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String domain,
        String path, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static String readCookie(HttpServletRequest request, String name) {

        assert name != null;

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }

    public static void removeCookie(HttpServletResponse response, String name) {
        addCookie(response, name, null, 0);
    }

    public static void removeCookie(HttpServletResponse response, String path, String name) {
        addCookie(response, path, name, null, 0);
    }
}
